﻿using System;
using System.Reactive.Linq;
using AppKit;
using Foundation;
using QFramework;
using SoulCard;
using SoulCard.Mac;

namespace SounCard.Mac
{
    public class TextViewDelegate : NSTextViewDelegate
    {
        public event Action OnTextDidChangeEvent;


        public override void TextDidChange(NSNotification notification)
        {
            OnTextDidChangeEvent?.Invoke();
        }
    }

    public partial class ViewController : NSViewController,INSUrlConnectionDelegate
    {
        public ViewController(IntPtr handle) : base(handle)
        {
        }


        TextViewDelegate mTextViewDelegate = null;

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var token = HttpUtil.GetToken("liangxie", "jiayoulqy0324");

            var getAllCard = GetAllCards.DoGetAllCard(token);
            CachedCardDatas.Get().CardDatas = getAllCard;

            Reload();

            CompletedButton.Hidden = true;
            SaveButton.Hidden = true;
            RebackButton.Hidden = true;

            mTextViewDelegate = new TextViewDelegate();
            TextView.Delegate = mTextViewDelegate;

            //Observable.Interval(TimeSpan.FromSeconds(30))
                      //.Subscribe(_ =>
                      //{
                      //    token = HttpUtil.GetToken("liangxie", "jiayoulqy0324");

                      //    getAllCard = GetAllCards.DoGetAllCard(token);
                      //    CachedCardDatas.Get().CardDatas = getAllCard;

                      //    Reload();
                      //});
        }

        public override NSObject RepresentedObject
        {
            get
            {
                return base.RepresentedObject;
            }
            set
            {
                base.RepresentedObject = value;
                // Update the view, if already loaded.
            }
        }

        void Reload()
        {
            TodoTable.DataSource = new TableDataSource(CachedCardDatas.Get().CardDatas);
            TodoTable.Delegate = new TableDelegate(this);
        }

        string mCurrentSelectedId = string.Empty;

        IDisposable mFromEventDisposable;

        public void OnTodoItemSelected(string id)
        {
            if (id != mCurrentSelectedId)
            {
                if (mFromEventDisposable != null)
                {
                    mFromEventDisposable.Dispose();
                    mFromEventDisposable = null;
                }

                CompletedButton.Hidden = true;
                SaveButton.Hidden = true;
                RebackButton.Hidden = true;


                TextView.TextStorage.SetString(new NSAttributedString(string.Empty));
            }

            var selectedCardData = CachedCardDatas.Get().CardDatas.Find(cardData => cardData.Id == id);

            mCurrentSelectedId = selectedCardData.Id;

            TextView.TextStorage.SetString(new NSAttributedString(selectedCardData.Content));


            mFromEventDisposable = Observable.FromEvent(action => mTextViewDelegate.OnTextDidChangeEvent += action, Action => mTextViewDelegate.OnTextDidChangeEvent -= Action)
                      .Subscribe(_ =>
                      {
                          if (TextView.String != selectedCardData.Content)
                          {
                              SaveButton.Hidden = false;
                          }
                          else
                          {
                              SaveButton.Hidden = true;
                          }
                      });

            if (selectedCardData.Complete)
            {
                CompletedButton.Hidden = true;
                RebackButton.Hidden = false;
            }
            else
            {
                CompletedButton.Hidden = false;
                RebackButton.Hidden = true;
            }
        }

        partial void OnTextField(NSTextField sender)
        {
            Console.WriteLine(sender.StringValue);

            View.AddSubview(new NSTextField()
            {
                StringValue = sender.StringValue
            });

            NSUserDefaults.StandardUserDefaults.SetString(sender.StringValue, "storeName");
        }

        partial void OnAddNewTodoItem(NSObject sender)
        {
            var todoContent = NewTodoContent.StringValue;

            CachedCardDatas.Get().CardDatas.Add(new CardData("1") { Content = todoContent });

            Reload();
        }

        internal void Delete(NSString id)
        {
            var token = HttpUtil.GetToken("liangxie", "jiayoulqy0324");

            DeleteCard.DoDeleteCard(id, token);

            var getAllCard = GetAllCards.DoGetAllCard(token);
            CachedCardDatas.Get().CardDatas = getAllCard;


            Reload();
        }
    }
}
